package other

import (
	"data/config"
	"public/mylog"
	"public/mysqldb"
)

func GetRegionLevel() (result []*Region_info) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	//省
	orm.Table("region_config_tbl").Select("province as name").Group("province").Find(&result)

	if len(result) > 0 {
		for _, v := range result {
			var city []*Region_info //市
			orm.Table("region_config_tbl").Select("city as name").Group("city").Where("province = ?", v.Name).Find(&city)
			if len(city) == 1 && city[0].Name == "" {
				city = nil
			}
			if len(city) > 0 {
				for _, k := range city {
					var region []*Region_info //区域
					orm.Table("region_config_tbl").Select("region as name").Where("province = ? and city = ?", v.Name, k.Name).Find(&region)
					if len(region) == 1 && region[0].Name == "" {
						region = nil
					}
					k.Children = region
				}
			}
			v.Children = city
		}
	}

	return
}

//编辑图片
func UpdatePicByModule(module, pic string) bool {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	err := orm.Table("pic_info_tbl").Where("module = ?", module).Update("pic", pic).Error
	if err != nil {
		mylog.Error(err)
		return false
	} else {
		return true
	}
}

//获取图片 module：空则默认全部
func GetPic(module string) (result map[string]string) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())

	var tmp []Pic_info_tbl
	if len(module) > 0 {
		orm.Where("module = ?", module).Find(&tmp)
	} else {
		orm.Find(&tmp)
	}
	if len(tmp) > 0 {
		result = make(map[string]string)
		for _, v := range tmp {
			result[v.Module] = v.Pic
		}
	}
	return
}

//获取省市区
func OnGetRegion(province, city, region string) (result Region_config_tbl) {
	var db mysqldb.MySqlDB
	defer db.OnDestoryDB()
	orm := db.OnGetDBOrm(config.GetDbUrl())
	orm.Where("province = ? and city = ? and region = ? ", province, city, region).Find(&result)
	return
}
